﻿using FrameworkCore.Modules;
using Microsoft.AspNetCore.Routing;

namespace FrameworkCore.Mvc;

#nullable disable

/// <summary>
/// 表示路由发布者的实现接口
/// </summary>
public class RoutePublisher : IRoutePublisher
{
    #region 字段

    /// <summary>
    /// 类型查找器
    /// </summary>
    protected readonly ITypeFinder _typeFinder;

    #endregion

    #region 构造函数

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="typeFinder">类型查找器</param>
    public RoutePublisher(ITypeFinder typeFinder)
    {
        _typeFinder = typeFinder;
    }

    #endregion

    #region 方法

    /// <summary>
    /// 注册路由
    /// </summary>
    /// <param name="endpointRouteBuilder">路由建造器</param>
    public virtual void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder)
    {
        // 查找其他程序集提供的路由提供者
        var routeProviders = _typeFinder.FindClassesOfType<IRouteProvider>();

        // 创建并排序路由提供者的实例
        var instances = routeProviders
            .Select(routeProvider => (IRouteProvider)Activator.CreateInstance(routeProvider))
            .OrderByDescending(routeProvider => routeProvider.Priority);

        // 注册所有提供的路由
        foreach (var routeProvider in instances)
            routeProvider.RegisterRoutes(endpointRouteBuilder);
    }

    #endregion
}
